package com.taorenqi.business.fragment.main;


import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.orhanobut.dialogplus.DialogPlus;
import com.taorenqi.business.R;
import com.taorenqi.business.activity.PermissionsActivity;
import com.taorenqi.business.app.MyApp;
import com.taorenqi.business.event.PayEvent;
import com.taorenqi.business.event.PersonalEvent;
import com.taorenqi.business.event.RechargeEvent;
import com.taorenqi.business.event.StartFragmentEvent;
import com.taorenqi.business.fragment.base.BaseMainFragment;
import com.taorenqi.business.fragment.login.CompleteInfoFragment;
import com.taorenqi.business.fragment.mine.GiftFragment;
import com.taorenqi.business.fragment.mine.HelpFragment;
import com.taorenqi.business.fragment.mine.MoneyDetailFragment;
import com.taorenqi.business.fragment.mine.PopularityFragment;
import com.taorenqi.business.fragment.mine.RebateFragment;
import com.taorenqi.business.fragment.mine.RechargeFragment;
import com.taorenqi.business.fragment.mine.RechargeManageFragment;
import com.taorenqi.business.fragment.mine.VipFragment;
import com.taorenqi.business.fragment.mine.insideinfo.InsideInformationFragment;
import com.taorenqi.business.fragment.mine.more.MoreFragment;
import com.taorenqi.business.helper.BannerViewHolder;
import com.taorenqi.business.utils.ImageUtils;
import com.taorenqi.business.utils.ToastUtil;
import com.taorenqi.business.widget.image.CircleImageView;
import com.taorenqi.business.widget.statusview.StatusView;
import com.taorenqi.business.widget.subscribers.PageDataSubscriberOnNext;
import com.taorenqi.business.widget.subscribers.ProgressSubscriber;
import com.taorenqi.data.common.BasePageableResponse;
import com.taorenqi.data.entity.mine.BannerListEntity;
import com.taorenqi.data.entity.mine.UserCenterEntity;
import com.taorenqi.data.service.MineDataHttpRequest;
import com.taorenqi.imagepicker.AndroidImagePicker;
import com.thefinestartist.finestwebview.FinestWebView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class MineFragment extends BaseMainFragment {


    @Bind(R.id.convenientbanner)
    ConvenientBanner mConvenientbanner;
    @Bind(R.id.mine_money)
    TextView mineMoney;
    @Bind(R.id.mine_popularity)
    TextView minePopularity;
    @Bind(R.id.mine_manage)
    TextView mineManage;
    @Bind(R.id.mine_gift)
    TextView mineGift;
    @Bind(R.id.mine_info)
    TextView mineInfo;
    @Bind(R.id.mine_help)
    TextView mineHelp;
    @Bind(R.id.mine_more)
    TextView mineMore;
    @Bind(R.id.nested_scroll_view)
    NestedScrollView nestedScrollView;
    @Bind(R.id.status_view)
    StatusView statusView;
    @Bind(R.id.root_layout)
    FrameLayout rootLayout;
    @Bind(R.id.mine_civ_avatar)
    CircleImageView mineCivAvatar;
    @Bind(R.id.mine_username)
    TextView mineUsername;
    @Bind(R.id.mine_iv_vip)
    ImageView mineIvVip;
    @Bind(R.id.mine_tv_vip)
    TextView mineTvVip;
    @Bind(R.id.mine_ll)
    LinearLayout mineLl;
    @Bind(R.id.mine_super_vip)
    Button mineSuperVip;
    @Bind(R.id.mine_gb)
    TextView mineGb;
    @Bind(R.id.mine_gb_number)
    TextView mineGbNumber;
    @Bind(R.id.mine_renqi)
    TextView mineRenqi;
    @Bind(R.id.mine_renqi_number)
    TextView mineRenqiNumber;
    @Bind(R.id.mine_btn_recharge)
    Button mineBtnRecharge;
    @Bind(R.id.mine_kefu_qq)
    ImageView mineKefuQq;
    @Bind(R.id.mine_rebate)
    TextView mineRebate;

    private List<String> networkImages;
    private List<String> bannerLink;
    private DialogPlus dialogPlus;

    private BasePageableResponse<UserCenterEntity> data;
    private BasePageableResponse<BannerListEntity> bannerEntity;
    private PageDataSubscriberOnNext<BasePageableResponse<UserCenterEntity>> subscriber;
    private PageDataSubscriberOnNext<BasePageableResponse<BannerListEntity>> subscriberBanner;

    public static MineFragment newInstance() {
        // Required empty public constructor
        MineFragment fragment = new MineFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        httpRequest();
        return view;
    }

    private void httpRequest() {
        subscriber = new PageDataSubscriberOnNext<BasePageableResponse<UserCenterEntity>>() {
            @Override
            public void onNext(BasePageableResponse<UserCenterEntity> entity) {
                data = entity;
                if (data != null) {
                    UserCenterEntity centerEntity = data.getDatalist().get(0);
                    mineUsername.setText(centerEntity.getMobile() + "");
                    mineGbNumber.setText(centerEntity.getBalance() + "");
                    mineRenqiNumber.setText(centerEntity.getRqz() + "");
                    int vipLevel = centerEntity.getViplvl();
                    String[] split = centerEntity.getVipoverdate().split(" ");
                    String number = split[0];

                    switch (vipLevel) {
                        case 0://普通用户
                            mineIvVip.setImageResource(R.drawable.feivip);
                            mineTvVip.setText("非VIP，升级享受特权");
                            mineSuperVip.setText("升至尊VIP");
                            break;

                        case 1://vip用户
                            mineIvVip.setImageResource(R.drawable.vip);
                            mineTvVip.setText("VIP，" + number + "到期");
                            mineSuperVip.setText("升至尊VIP");
                            break;
                        case 2://svip
                            mineIvVip.setImageResource(R.drawable.svip);
                            mineTvVip.setText("SVIP，" + number + "到期");
                            mineSuperVip.setText("升至尊VIP");
                            break;

                        case 3://svip+
                            mineIvVip.setImageResource(R.drawable.zhizun);
                            mineTvVip.setText("至尊VIP" + number + "到期");
                            mineSuperVip.setText("最高级");
                            break;
                        default:
                            break;
                    }
                }

            }
        };
        MineDataHttpRequest.getInstance(MyApp.getApp()).getUserCenter(new ProgressSubscriber(subscriber, _mActivity));

        subscriberBanner = new PageDataSubscriberOnNext<BasePageableResponse<BannerListEntity>>() {
            @Override
            public void onNext(BasePageableResponse<BannerListEntity> entity) {

                bannerEntity = entity;
                networkImages = new ArrayList<String>();
                bannerLink = new ArrayList<String>();

                for (int i = 0; i < bannerEntity.getDatalist().size(); i++) {
                    networkImages.add(bannerEntity.getDatalist().get(i).getBanner_img());
                    bannerLink.add(bannerEntity.getDatalist().get(i).getBanner_url());
                }

                initBanner();
            }
        };

        MineDataHttpRequest.getInstance(MyApp.getApp()).getBannerList(new ProgressSubscriber(subscriberBanner, _mActivity));
    }

    private void initBanner() {

        mConvenientbanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {

                new FinestWebView
                        .Builder(MyApp.getApp())
                        .theme(R.style.FinestWebViewTheme)
//                        .titleDefault(titleList.get(position))
                        .showUrl(false)
                        .statusBarColorRes(R.color.colorPrimary)
                        .toolbarColorRes(R.color.colorPrimary)
                        .titleColorRes(R.color.finestWhite)
                        .urlColorRes(R.color.finestWhite)
                        .iconDefaultColorRes(R.color.finestWhite)
                        .progressBarColorRes(R.color.finestWhite)
                        .stringResCopiedToClipboard(R.string.copied_to_clipboard)
                        .stringResCopiedToClipboard(R.string.copied_to_clipboard)
                        .stringResCopiedToClipboard(R.string.copied_to_clipboard)
                        .showSwipeRefreshLayout(true)
                        .swipeRefreshColorRes(R.color.colorPrimary)
                        .menuSelector(R.drawable.selector_light_theme)
                        .menuTextGravity(Gravity.CENTER)
                        .menuTextPaddingRightRes(R.dimen.defaultMenuTextPaddingLeft)
                        .dividerHeight(0)
                        .gradientDivider(false)
                        .setCustomAnimations(R.anim.slide_up, R.anim.hold, R.anim.hold, R.anim.slide_down)
                        .show(bannerLink.get(position));
            }
        });

        mConvenientbanner.setPages(new CBViewHolderCreator<BannerViewHolder>() {
            @Override
            public BannerViewHolder createHolder() {
                return new BannerViewHolder();
            }
        }, networkImages)
                //轮播时间
                .startTurning(3000)
                //小圆点
                .setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused});
    }

    @Override
    public void onDestroyView() {
        AndroidImagePicker.getInstance().onDestroy();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @OnClick({R.id.mine_rebate, R.id.mine_money, R.id.mine_popularity, R.id.mine_manage, R.id.mine_gift
            , R.id.mine_info, R.id.mine_help, R.id.mine_more, R.id.mine_civ_avatar,
            R.id.mine_super_vip, R.id.mine_btn_recharge, R.id.mine_kefu_qq
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mine_rebate://邀请返利
                EventBus.getDefault().post(new StartFragmentEvent(RebateFragment.newInstance()));
                break;
            case R.id.mine_money://资金明细
                EventBus.getDefault().post(new StartFragmentEvent(MoneyDetailFragment.newInstance()));
                break;
            case R.id.mine_popularity://人气值
                EventBus.getDefault().post(new StartFragmentEvent(PopularityFragment.newInstance()));
                break;
            case R.id.mine_manage://充值管理
                EventBus.getDefault().post(new StartFragmentEvent(RechargeManageFragment.newInstance()));
                break;
            case R.id.mine_gift://我的礼券
                EventBus.getDefault().post(new StartFragmentEvent(GiftFragment.newInstance()));
                break;
            case R.id.mine_info://站内信息
                EventBus.getDefault().post(new StartFragmentEvent(InsideInformationFragment.newInstance()));
                break;
            case R.id.mine_help://帮助指南
                EventBus.getDefault().post(new StartFragmentEvent(HelpFragment.newInstance()));
                break;
            case R.id.mine_more://更多
                EventBus.getDefault().post(new StartFragmentEvent(MoreFragment.newInstance()));
                break;
            case R.id.mine_civ_avatar://头像
//                if (MyApp.getApp().getPermissionsChecker().lacksPermissions(MyApp.getApp().FILE_CAMERA)) {
//                    PermissionsActivity.startActivityForResult(_mActivity, MyApp.getApp().REQUEST_CODE, MyApp.getApp().FILE_CAMERA);
//                } else {
//                    AndroidImagePicker.getInstance().pickAndCrop(_mActivity, true, 120, new AndroidImagePicker.OnImageCropCompleteListener() {
//                        @Override
//                        public void onImageCropComplete(Bitmap bmp, float ratio) {
//
//                            Glide.with(_mActivity)
//                                    .load(ImageUtils.bitmap2Bytes(bmp, Bitmap.CompressFormat.JPEG))
//                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
//                                    .centerCrop()
//                                    .dontAnimate()
//                                    .thumbnail(0.5f)
//                                    .placeholder(R.mipmap.ic_default_avatar)
//                                    .error(R.mipmap.ic_default_avatar)
//                                    .into(mineCivAvatar);
//                        }
//                    });
//
//                    return;
//
//                }
                break;
            case R.id.mine_super_vip://至尊vip
                EventBus.getDefault().post(new StartFragmentEvent(VipFragment.newInstance()));
                break;
            case R.id.mine_btn_recharge://充值
                EventBus.getDefault().post(new StartFragmentEvent(RechargeFragment.newInstance()));
                break;
            case R.id.mine_kefu_qq://客服QQ
                if (isQQClientAvailable(_mActivity)) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://wpa.b.qq.com/cgi/wpa.php?ln=2&uin=4006331298")));
                } else {
                    ToastUtil.showToast(_mActivity, "请安装QQ");
                }
                break;
        }
    }

    @Subscribe
    public void onEvent(PayEvent event) {
        httpRequest();
    }

    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

}
